package ecnu.ecgbackend.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import ecnu.ecgbackend.config.redis.RedisService;
import ecnu.ecgbackend.entity.User;
import ecnu.ecgbackend.utils.JwtUtils;
import ecnu.ecgbackend.utils.LoginResult;
import ecnu.ecgbackend.utils.ResultCode;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        User user=(User) authentication.getPrincipal();
        String token=jwtUtils.generateToken(user);
        long expireTime= Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(token.replace("jwt_",""))
                .getBody().getExpiration().getTime();
        LoginResult loginResult=new LoginResult(user.getId(),token,expireTime);
        String result= JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        String tokenKey="token_"+token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration()/1000);
        ServletOutputStream outputStream=response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
